package com.thon.controller.rest;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thon.commons.persistence.Page;
import com.thon.commons.utils.CacheUtils;
import com.thon.commons.utils.DateUtils;
import com.thon.controller.util.BaseController;
import com.thon.entity.paper.Paper;
import com.thon.entity.paper.Relation;
import com.thon.entity.system.User;
import com.thon.entity.topic.Choice;
import com.thon.entity.topic.Topic;
import com.thon.service.paper.RelationService;
import com.thon.service.system.SystemService;
import com.thon.service.topic.ChoiceService;
import com.thon.service.topic.TopicService;
import com.thon.service.utils.UserUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Chen on 2016/2/9.
 */
@Controller
@RequestMapping("/api/topic")
public class TopicRestController extends BaseController{

    @Autowired
    private TopicService topicService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ChoiceService choiceService;
    @Autowired
    private RelationService relationService;


    //出题
    @RequestMapping(value="/save", method = RequestMethod.POST)
    public ResponseEntity<?> apiTopicSave(@Valid Topic topic) {

        if(topic.getCreateDate() == null){
            topic.setCreateDate(new Date());
        }
        //教务代替教师或学生出题
        if("admin".equals(UserUtils.getUser().getRole().getEnname())){
            topic.setPass(3);
            topicService.saveTopic(topic);
            return new ResponseEntity(true, HttpStatus.OK);
        }
        //教师出题
        else if ("teacher".equals(UserUtils.getUser().getRole().getEnname())) {
            topic.setPass(1);
            topic.setCreatorType(0);
            topic.setDirectTeacher(UserUtils.getUser());
            topic.setCreator(UserUtils.getUser());
            topicService.saveTopic(topic);
            return new ResponseEntity(true, HttpStatus.OK);
        }
        //学生出题
        else if ("student".equals(UserUtils.getUser().getRole().getEnname())) {
            if (!topicService.hasPushTopic(UserUtils.getUser().getId())) {
                topic.setPass(0);
                topic.setCreatorType(1);
                topic.setCreator(UserUtils.getUser());
                topic.setSource(3);
                topic.setRestriction(1);
                topicService.saveTopic(topic);
                //更新进度
                User user = UserUtils.getUser();
                user.setSchedule(1);
                systemService.saveUser(user);
                return new ResponseEntity(true, HttpStatus.OK);
            } else {
                return new ResponseEntity(false, HttpStatus.OK);
            }
        }
        else {
            return new ResponseEntity(true, HttpStatus.OK);
        }
    }


    //学生申请选题
    @RequestMapping(value="/student/ask_for", method = RequestMethod.POST)
    public ResponseEntity<?> apiStudentAskForTopic(@RequestParam(value = "id", required = true) int id){
        Topic topic = topicService.getTopic(id);
        //只能选择已通过教务审核的题目
        if(topic.getPass() == 3){
            //没有选择题目
            if(choiceService.ifChoice(UserUtils.getUser().getId())){
                //更新出题表当前人数
                Integer oldStudentNumber = topic.getStudentNumber();
                if(oldStudentNumber <= topic.getRestriction()){
                    topic.setStudentNumber(oldStudentNumber + 1);
                    topicService.saveTopic(topic);
                }
                //保存至选题表
                Choice choice = new Choice();
                choice.setTopic(topic);
                choice.setStudent(UserUtils.getUser());
                choice.setStatus(0);
                choiceService.saveChoice(choice);
                //更新进度
                User user = UserUtils.getUser();
                user.setSchedule(3);
                systemService.saveUser(user);
                return new ResponseEntity("true", HttpStatus.OK);
            }else{
                return new ResponseEntity("false", HttpStatus.OK);
            }
        }
        return new ResponseEntity("edu_no_pass", HttpStatus.OK);
    }

    //教务审核出题通过
    @RequestMapping(value="/educator/pass", method = RequestMethod.POST)
    public ResponseEntity<?> apiEduTopicPass(@RequestParam(value = "id",required = true) int id) {

        Topic topic = topicService.getTopic(id);
        if(topic.getPass() == 1){
            topic.setPass(3);
            topicService.saveTopic(topic);
            //更新进度
            User user = UserUtils.getUser();
            user.setSchedule(2);
            systemService.saveUser(user);
            return new ResponseEntity("true", HttpStatus.OK);
        } else if (topic.getPass() == 3) {
            return new ResponseEntity("edu_success", HttpStatus.OK);
        } else if (topic.getPass() == 0) {
            return new ResponseEntity("tch_wait", HttpStatus.OK);
        } else if (topic.getPass() == 2) {
            return new ResponseEntity("tch_false", HttpStatus.OK);
        } else {
            return new ResponseEntity("ech_false", HttpStatus.OK);
        }
    }

    //教师审核学生出题通过
    @RequestMapping(value="/teacher/pass", method = RequestMethod.POST)
    public ResponseEntity<?> apiTchStdTopicPass(@RequestParam(value = "id",required = true) int id) {

        Topic topic = topicService.getTopic(id);
        if (topic.getPass() == 0 || topic.getPass() == 2) {
            topic.setPass(1);
            topicService.saveTopic(topic);
            return new ResponseEntity("true", HttpStatus.OK);
        } else if (topic.getPass() == 1) {
            return new ResponseEntity("had_pass", HttpStatus.OK);
        } else if (topic.getPass() == 3) {
            return new ResponseEntity("had_educator_pass", HttpStatus.OK);
        } else {
            return new ResponseEntity("had_educator_nopass", HttpStatus.OK);
        }
    }

    //教师审核学生出题不通过
    @RequestMapping(value="/teacher/nopass", method = RequestMethod.POST)
    public ResponseEntity<?> apiTchStdTopicNoPass(@RequestParam(value = "id",required = true) int id) {

        Topic topic = topicService.getTopic(id);
        if (topic.getPass() == 0 || topic.getPass() == 1 ) {
            topic.setPass(2);
            topicService.saveTopic(topic);
            //更新进度
            User user = UserUtils.getUser();
            user.setSchedule(1);
            systemService.saveUser(user);
            return new ResponseEntity("true", HttpStatus.OK);
        } else if (topic.getPass() == 2) {
            return new ResponseEntity("had_nopass", HttpStatus.OK);
        } else if (topic.getPass() == 3) {
            return new ResponseEntity("had_educator_pass", HttpStatus.OK);
        } else {
            return new ResponseEntity("had_educator_nopass", HttpStatus.OK);
        }
    }

    //查看出题详情
    @RequestMapping(value="/details", method = RequestMethod.GET)
    public ResponseEntity<?> apiTopicDetails(@RequestParam(value = "id",required = true) int id) {
        Map<String, Object> dataMap = Maps.newHashMap();
        Topic topic = topicService.getTopic(id);
        dataMap.put("topic",topic);
        return new ResponseEntity(dataMap, HttpStatus.OK);
    }

    //查看选题详情
    @RequestMapping(value="/choice/details", method = RequestMethod.GET)
    public ResponseEntity<?> apiChoiceDetails(@RequestParam(value = "id",required = true) int id) {
        Map<String, Object> dataMap = Maps.newHashMap();
        Choice choice = choiceService.getChoice(id);
        dataMap.put("choice",choice);
        return new ResponseEntity(dataMap, HttpStatus.OK);
    }

    //删除出题
    @RequestMapping(value="/del", method = RequestMethod.POST)
    public ResponseEntity<?> apiTopicDel(@RequestParam(value = "id",required = true) int id) {
        if(UserUtils.getUser().isAdmin()){
            Topic topic = topicService.getTopic(id);
            topicService.delTopic(topic);
            return new ResponseEntity("true", HttpStatus.OK);
        }else {
            return new ResponseEntity("false", HttpStatus.FORBIDDEN);
        }
    }

    //查看所有出题
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseEntity<?> topicList(@RequestParam(value = "p", defaultValue = "1") int pageNo,
                                  @RequestParam(value = "s", defaultValue = PAGE_SIZE) int pageSize,
                                  Topic topic) {

        Page<Topic> page = new Page<Topic>();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        page = topicService.findTopics(page,topic);

        return new ResponseEntity(page, HttpStatus.OK);
    }


    @RequestMapping(value="/choice/save", method = RequestMethod.POST)
    public ResponseEntity<?> apiChoiceSave(@Valid Choice choice) {

        if(choice.getChoiceDate() == null){
            choice.setChoiceDate(new Date());
        }
        if(UserUtils.getUser().getRole().getId() == 3 && choice.getStatus() == null){
            User student = systemService.getUser(UserUtils.getUser().getId());
            choice.setStudent(student);
            //创建论文关系表
            Relation relation = new Relation();
            relation.setStudent(student);
            if(choice.getTopic() != null && choice.getTopic().getCreator() != null){
                relation.setTeacher(choice.getTopic().getCreator());
            }
        }
        choiceService.saveChoice(choice);

        return new ResponseEntity(true, HttpStatus.OK);
    }

    @RequestMapping(value="/choice/del", method = RequestMethod.POST)
    public ResponseEntity<?> apiChoiceDel(@RequestParam(value = "id",required = true) int id) {
        if(UserUtils.getUser().isAdmin()){
            Choice choice = choiceService.getChoice(id);
            choiceService.delChoice(choice);
            return new ResponseEntity("true", HttpStatus.OK);
        }else {
            return new ResponseEntity("false", HttpStatus.FORBIDDEN);
        }
    }

    //查看所有选题
    @RequestMapping(value = "/choice/list", method = RequestMethod.GET)
    public ResponseEntity<?> choiceList(@RequestParam(value = "p", defaultValue = "1") int pageNo,
                                  @RequestParam(value = "s", defaultValue = PAGE_SIZE) int pageSize,
                                  Choice choice) {

        Page<Choice> page = new Page<Choice>();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        page = choiceService.findChoices(page,choice);
        return new ResponseEntity(page, HttpStatus.OK);
    }

    //学生取消选题
    @RequestMapping(value = "/choice/change", method = RequestMethod.POST)
    public ResponseEntity<?> apiChoiceChange(@RequestParam(value = "id",required = true) int id) {

        Choice choice = choiceService.getChoice(id);
        if (choice.getStatus() != 3) {
            choice.setDelFlag(1);
            Topic topic = choice.getTopic();
            topic.setStudentNumber(topic.getStudentNumber() - 1);
            choiceService.saveChoice(choice);
            //更新进度
            User user = UserUtils.getUser();
            user.setSchedule(0);
            systemService.saveUser(user);
            return new ResponseEntity(true, HttpStatus.OK);
        }else{
            return new ResponseEntity(false, HttpStatus.OK);
        }
    }

    //教师审核选题通过
    @RequestMapping(value = "/choice/pass", method = RequestMethod.POST)
    public ResponseEntity<?> apiChoiceTeacherPass(@RequestParam(value = "id",required = true) int id) {

        Choice choice = choiceService.getChoice(id);
        if (choice.getStatus() == 0 || choice.getStatus() == 2) {
            choice.setStatus(1);
            choiceService.saveChoice(choice);
            return new ResponseEntity("true", HttpStatus.OK);
        } else if (choice.getStatus() == 1) {
            return new ResponseEntity("had_pass", HttpStatus.OK);
        } else if (choice.getStatus() == 3) {
            return new ResponseEntity("edu_pass", HttpStatus.OK);
        } else {
            return new ResponseEntity("edu_nopass", HttpStatus.OK);
        }
    }

    //教师审核选题不通过
    @RequestMapping(value = "/choice/nopass", method = RequestMethod.POST)
    public ResponseEntity<?> apiChoiceTeacherNoPass(@RequestParam(value = "id",required = true) int id) {

        Choice choice = choiceService.getChoice(id);
        if (choice.getStatus() == 0 || choice.getStatus() == 1) {
            choice.setStatus(2);
            choiceService.saveChoice(choice);
            //更新进度
            User user = UserUtils.getUser();
            user.setSchedule(3);
            systemService.saveUser(user);
            return new ResponseEntity("true", HttpStatus.OK);
        } else if (choice.getStatus() == 2) {
            return new ResponseEntity("had_nopass", HttpStatus.OK);
        } else if (choice.getStatus() == 3) {
            return new ResponseEntity("edu_pass", HttpStatus.OK);
        } else {
            return new ResponseEntity("edu_nopass", HttpStatus.OK);
        }
    }


    //教务审核选题通过
    @RequestMapping(value="/choice/educator/pass", method = RequestMethod.POST)
    public ResponseEntity<?> apiChoiceEducatorPass(@RequestParam(value = "id",required = true) int id) {

        Choice choice = choiceService.getChoice(id);
        if (choice.getDelFlag() == 0) {
            if (choice.getStatus() == 1 || choice.getStatus() == 4) {
                choice.setStatus(3);
                choiceService.saveChoice(choice);
                //更新进度
                User user = choice.getStudent();
                user.setSchedule(4);
                systemService.saveUser(user);
                //建立论文关系,允许上传论文
                Relation relation = new Relation();
                User student = choice.getStudent();
                User teacher = choice.getTopic().getDirectTeacher();
                relation.setStudent(student);
                relation.setTeacher(teacher);
                relationService.saveRelation(relation);
                return new ResponseEntity("true", HttpStatus.OK);
            } else if (choice.getStatus() == 3) {
                return new ResponseEntity("had_pass", HttpStatus.OK);
            } else if (choice.getStatus() == 0) {
                return new ResponseEntity("wait_teacher", HttpStatus.OK);
            } else {
                return new ResponseEntity("teacher_nopass", HttpStatus.OK);
            }
        } else {
            return new ResponseEntity("invalid", HttpStatus.OK);
        }

    }

    //教务审核选题不通过
    @RequestMapping(value = "/choice/educator/nopass", method = RequestMethod.POST)
    public ResponseEntity<?> apiChoiceEducatorNoPass(@RequestParam(value = "id",required = true) int id) {

        Choice choice = choiceService.getChoice(id);
        if (choice.getDelFlag() == 0) {
            if (choice.getStatus() == 1 || choice.getStatus() == 3) {
                choice.setStatus(4);
                choiceService.saveChoice(choice);
                //更新进度
                User user = UserUtils.getUser();
                user.setSchedule(3);
                systemService.saveUser(user);
                return new ResponseEntity("true", HttpStatus.OK);
            } else if (choice.getStatus() == 4) {
                return new ResponseEntity("had_nopass", HttpStatus.OK);
            } else if (choice.getStatus() == 0) {
                return new ResponseEntity("wait_teacher", HttpStatus.OK);
            } else {
                return new ResponseEntity("teacher_nopass", HttpStatus.OK);
            }
        } else {
            return new ResponseEntity("invalid", HttpStatus.OK);
        }

    }

}
